package com.example.experiment12;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.IOException;

/**
 * @author CoderXshuai
 * @date 2021/4/4
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //录制请求码
    private final int RECORD_CODE = 100;
    //开始按钮
    private Button btnStart;
    //结束按钮
    private Button btnEnd;
    private MediaProjectionManager mediaProjectionManager;
    private MediaRecorder mediaRecorder;
    //录制文件的PPI
    private int scDpi;
    //录制文件的宽度
    private int scWidth;
    //录制文件的长度
    private int scHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = findViewById(R.id.btn_start);
        btnEnd = findViewById(R.id.btn_end);
        //获取屏幕尺寸
        getScreenSize();
        //获取权限
        getRecordPermission();
        //绑定监听器
        btnEnd.setOnClickListener(this);
        btnStart.setOnClickListener(this);
    }

    /**
     * 权限申请
     */
    private void getRecordPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
            Intent intent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(intent, RECORD_CODE);
        }
    }

    /**
     * 申请录制屏幕的结果回调
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        携带的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == RECORD_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
                mediaRecorder = getMediaRecorder();
                VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("capture", scWidth, scHeight, scDpi,
                        DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
            }
        }
    }

    /**
     * 初始化获取MediaRecorder实例
     *
     * @return MediaRecorder实例
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private MediaRecorder getMediaRecorder() {
        MediaRecorder mMedia = new MediaRecorder();
        //音频源
        mMedia.setAudioSource(MediaRecorder.AudioSource.MIC);
        //视频源
        mMedia.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        //视频输出格式
        mMedia.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //音频和视频编码格式
        mMedia.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        mMedia.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //视频尺寸
        mMedia.setVideoSize(scWidth, scHeight);
        //视频帧率
        mMedia.setVideoFrameRate(30);
        //视频比特率
        mMedia.setVideoEncodingBitRate(3 * 1024 * 1024);
        //旋转角度
        mMedia.setOrientationHint(0);
        //录屏文件存储路径
        String STORE_PATH = "/sdcard/DCIM/";
        File dir = new File(STORE_PATH);
        String filename = System.currentTimeMillis() / 1000 + ".mp4";
        String filePath = dir + "/" + filename;
        //视频输出路径
        mMedia.setOutputFile(filePath);
        try {
            mMedia.prepare();
        } catch (IOException | IllegalStateException e) {
            e.printStackTrace();
        }
        return mMedia;
    }

    /**
     * 获取屏幕属性
     */
    private void getScreenSize() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        scDpi = dm.densityDpi;
        scWidth = dm.widthPixels;
        scHeight = dm.heightPixels;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //开始录制
            case R.id.btn_start:
                try {
                    mediaRecorder.start();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
                break;
            //结束录制
            case R.id.btn_end:
                try {
                    mediaRecorder.stop();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}